﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace QYmall.Core.API.Controllers.Application
{
    /// <summary>
    /// 授权登录记录接口
    /// </summary>
    [Route("admin/oauth/login")]
    [ApiController]
    public class OAuthLoginController : ControllerBase
    {
        private readonly IOAuthLoginService _oAuthLoginService;
        private readonly IMapper _mapper;
        public OAuthLoginController(IOAuthLoginService oAuthLoginService, IMapper mapper)
        {
            _oAuthLoginService = oAuthLoginService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/oauth/login?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("OAuth", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.TrimStart('-').IsPropertyExists<OAuthLoginDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OAuthLoginDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表
            var list = await _oAuthLoginService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => !searchParam.Keyword.IsNotNullOrEmpty() || (x.Provider != null && x.Provider.Contains(searchParam.Keyword)) || (x.User != null && x.User.UserName.Contains(searchParam.Keyword)),
                searchParam.OrderBy ?? "Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<OAuthLoginDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/oauth/login/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("OAuth", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int id)
        {
            if (!await _oAuthLoginService.ExistsAsync<OAuthLogin>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _oAuthLoginService.DeleteAsync<OAuthLogin>(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/admin/oauth/login?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("OAuth", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var listIds = Ids.ToIEnumerable<int>();
            if (listIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _oAuthLoginService.DeleteAsync<OAuthLogin>(x => listIds.Contains(x.Id));

            return NoContent();
        }
        #endregion
    }
}
